<?php 
/* --------------------------------
 * Функции по работе с экспортом XML
 *  
 * 9 августа 2012
 * © Deemon 
 --------------------------------*/
 
 	Class UpdateCorsiniPrice
	{
		private $conn;
		private $elog;
		private $field_names;
		private $str_count_product = ''; 
		private $havent_code_str = '';
		private $count_updated = 0;
		private $messages = array();
		private $products = array();
		private $return_data = array( 'message' => '', 'codes' => array() );
		private $count_updated_products = array();
		private $count_updated_fields = 0;
		private $data_for_query = array();
		private $data_for_query_second = array();
		private $updated = array();
		private $all_corsini_codes = array();
		private $all_product_codes = array();
		private $banners = array();
		
		function startUpdateCorsini( $fine_name )
		{
			$this->setVariables();
			$this->getAllProductsID();
			$this->readFile( $fine_name );
			$this->prepareData();
			$this->startQuery();
			return $this->dispMessage();
		}
		
		function setVariables()
		{
			$this->conn = $GLOBALS['conn'];
			$this->elog = $GLOBALS['elog'];
			
			$this->field_names = array(
											'corsini_code',			// Код Корсини
											'price_retail',			// Цена
											'pp',					// ПП
											'pm',					// ПМ
											'pd',					// ПД
											'cbid'					// cbid
								);
		}
		
		private function getAllProductsID()
		{
			$this->conn->query( 'SELECT `product_code`, `corsini_code` FROM `store_products_view` WHERE `corsini_code` IS NOT NULL');
			while( $row = $this->conn->fetch() )
			{
				$this->all_corsini_codes[] = $row->corsini_code;
				$this->all_product_codes[$row->corsini_code] = $row->product_code;
			}
		}
		
		private function readFile( $fine_name )
		{
			$line = 0;
			$file = fopen( $_FILES[$fine_name]['tmp_name'] , 'r' );
			while( ( $data = fgetcsv( $file , '' , ';' , '"' ) ) !== FALSE )
			{
				if( $line++ != 0 )
				{
					foreach( $this->field_names as $i => $field_name )
						$product[$field_name] = isset( $data[$i] ) ? $data[$i] : '';
						
					if( !$this->checkCode( $line, $product['corsini_code'] ) ) continue;
					
					$this->products[$product['corsini_code']] = array_map( 'trim', $product );
				}
			}
		}
		
		private function checkCode( $line, $corsini_code )
		{
			if( !is_numeric( $corsini_code ) ) {
				$this->messages[] = 'Строка '.$line.'. Некорректный Корсини код.';
				return false; }
				
			if( !in_array( $corsini_code, $this->all_corsini_codes ) ) {
				$this->messages[] = 'Строка '.$line.'. Такого кода Корсини нет на сайте: '.$corsini_code;
				return false; }
			return true;
		}
		
		function prepareData()
		{
			foreach( $this->products as $corsini_code => $product )
			{
				foreach( $product as $field => $value )
				{
					if( $field != 'corsini_code' && strlen( $value ) > 0 )
					{
						if( !is_numeric( $value ) ) {
							$this->messages[] = 'Строка с кодом: '.$corsini_code.'. Некорректное значение в поле: '.$field;
							continue;
						}
						$this->data_for_query[$field]['value'][] = $value;
						$this->data_for_query[$field]['corsini_code'][] = $corsini_code;
						
						$this->count_updated_products[$corsini_code] = $this->all_product_codes[$corsini_code];
					}
				}
			}
		}
		
 		private function startQuery()
		{
 			foreach( $this->data_for_query as $field => $pr )
			{
				$this->count_updated_fields += count( $pr['value'] );
 				$this->conn->query('
					UPDATE `store_products` SET
					'.$field.' = ELT(FIELD( `corsini_code`, '.implode( $pr['corsini_code'], ', ' ).' ), '.implode( $pr['value'], ', ' ).' )
					WHERE `corsini_code` IN ( '.implode( $pr['corsini_code'], ', '  ).' )' );
			}
		}
		
		private function dispMessage()
		{
			$msg = '';
			
			foreach( $this->messages as $mess )
				$msg .= $mess.'<br />';
			
			$this->return_data['message'] = ( $msg ? '<br/><span class="red_str">'.$msg.'</span>' : '' ).'<br/>
				<h3 class="green_str">Количество обновленных товаров: '.count( $this->count_updated_products ).'<br/>
				Количество обновленных признаков: '.$this->count_updated_fields.'</h3>';
			
			$this->return_data['codes'] = $this->count_updated_products;
			return $this->return_data;
		}
	}
	